import { useStore } from "vuex";
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ILoginForm } from "@/interface";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
export function useLogin() {
  const loginFormRef = ref<FormInstance>();
  const loginForm: ILoginForm = reactive({
    user: "",
    password: "",
  });
  const rules = reactive<FormRules>({
    user: [{ required: true, message: "请输入用户名！", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码！", trigger: "blur" }],
  });

  const router = useRouter();
  const store = useStore();
  const loginHandle = async () => {
    try {
      await store.dispatch("user/login", { loginForm, router });
    } catch (e) {
      ElMessage({
        type: "error",
        message: e as string,
      });
    }
  };
  const submitHandle = async () => {
    if (!loginFormRef.value) return;
    const validate = await new Promise<boolean>((resolve) => {
      loginFormRef.value?.validate((valid: any) => {
        resolve(valid ? true : false);
      });
    });
    if (validate) {
      loginHandle();
    } else {
      console.log("error submit!");
    }
  };
  return {
    rules,
    loginForm,
    loginFormRef,
    submitHandle,
  };
}
